package aishua.com.mytestapplist.utils;

import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.ResolveInfo;
import android.content.pm.Signature;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.NetworkInfo.State;
import android.net.Uri;
import android.os.Environment;
import android.telephony.TelephonyManager;

import java.io.File;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

public class AndroidUtils {
	
	/** ����״̬:������ */
	public static final int NET_STATUS_ERROR = 0;
	
	/** ����״̬:WIFI */
	public static final int NET_STATUS_WIFI = 1;
	
	/** ����״̬:3G/2G */
	public static final int NET_STATUS_MOBILE = 2;
	
	
	/**
	 * ��ȡ�汾��
	 * @return ��ǰӦ�õİ汾��
	 */
	public static String getVersion(Context context) {
	    try {
	        PackageManager manager = context.getPackageManager();
	        PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
	        String version = info.versionName;
	        if (version.contains("ctch1")) {
	        	version = version.replace("ctch1", "");
	        }
	        return version;
	    } catch (Exception e) {
	        e.printStackTrace();
	    }
	    return "";
	}
	/**
	 * 插件本地版本号
	 * @param Package 包名
	 * @param context 
	 * @return
	 */
	public static String getLoaclPlugVersion(String packageName, Context context){
	    try {
	        PackageManager manager = context.getPackageManager();
	        PackageInfo info = manager.getPackageInfo(packageName, 0);
	        String version = info.versionName;
	        if (version.contains("ctch1")) {
	        	version = version.replace("ctch1", "");
	        }
	        return version;
	    } catch (Exception e) {
	        e.printStackTrace();
	    }
	    return "";
	}
	
	public static boolean isClientNeedUpdate(Context context,
											 String packageName, String newVersion) {
		boolean tag = false;
		PackageManager pManager = context.getPackageManager();
        try {
			PackageInfo pi = pManager.getPackageInfo(packageName, 0);
			if (pi == null) {
				return false;
			}
			String oldVersion = pi.versionName;
			if (oldVersion == null) {
				return false;
			}
			tag = compareVersion(oldVersion, newVersion);
		} catch (NameNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}  
        return tag;
	}
	
	/**
	 * ��װAPK
	 * @param context
	 * @param apkPath
	 */
	public static void installAPK(Context context, String apkPath) {
		
		File apkFile = new File(apkPath);
		if (apkFile.exists()) {
			Intent intent = new Intent(Intent.ACTION_VIEW);
			intent.setDataAndType(Uri.parse("file://" + apkFile.toString()),
					"application/vnd.android.package-archive");
			context.startActivity(intent);
		}
		
	}
	
	/**
	 * ж��APK
	 * @param context
	 * @param packageID
	 */
	public static void uninstallAPK(Context context, String packageID) {
		
		Uri packageURI = Uri.parse("package:" + packageID);
		Intent intent = new Intent(Intent.ACTION_DELETE, packageURI);
		context.startActivity(intent);
	}
	
	
	/**
	 * �ж�APK�Ƿ����
	 * @param context
	 * @param packageName
	 * @return
	 */
    public static boolean checkApkExist(Context context, String packageName) {
    	
		if (packageName == null || "".equals(packageName))
			return false;
		try {
			ApplicationInfo info = context.getPackageManager()
					.getApplicationInfo(packageName,
							PackageManager.GET_UNINSTALLED_PACKAGES);
			if (info != null) {
				return true;
			} 
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
		return false;
	}
    
    public static void openAPK(Context context, String packageName) {
	    try {
	      	PackageManager pManager = context.getPackageManager();
	      	PackageInfo pi = pManager.getPackageInfo(packageName, 0);
	        Intent resolveIntent = new Intent(Intent.ACTION_MAIN, null);
	        resolveIntent.setPackage(pi.packageName);  
	        List<ResolveInfo> apps = pManager.queryIntentActivities(
	                  resolveIntent, 0);  
	        ResolveInfo ri = apps.iterator().next();
	        if (ri != null) {
	            String className = ri.activityInfo.name;
	            Intent intent = new Intent(Intent.ACTION_MAIN);
	            ComponentName cn = new ComponentName(packageName, className);
	            intent.setComponent(cn);  
	            context.startActivity(intent);  
	        }  
	    } catch (NameNotFoundException e) {
	    	// TODO Auto-generated catch block   
	        e.printStackTrace();  
	    }  
    }
    
    public static boolean isAPkExist(Context context, String packageName) {

	    try {
	      	PackageManager pManager = context.getPackageManager();
	      	PackageInfo pi = pManager.getPackageInfo(packageName, 0);
	        Intent resolveIntent = new Intent(Intent.ACTION_MAIN, null);
	        resolveIntent.setPackage(pi.packageName);  
	        List<ResolveInfo> apps = pManager.queryIntentActivities(
	                  resolveIntent, 0);  
	        ResolveInfo ri = apps.iterator().next();
	        if (ri != null) {
	        	return true;
	        }  
	    } catch (NameNotFoundException e) {
	    	// TODO Auto-generated catch block   
	        e.printStackTrace();  
	    }  
	    
	    return false;
    
    }
    
    /**
     * �ж������Ƿ����
     * @param context
     * @return
     */
    public static boolean isNetworkConnected(final Context context) {
    	
    	if (context != null) { 
    		
    		ConnectivityManager mConnectivityManager = (ConnectivityManager) context
    				.getSystemService(Context.CONNECTIVITY_SERVICE);
    		NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
    		if (mNetworkInfo != null) { 
    			return mNetworkInfo.isAvailable(); 
    		}
    	}

    	return false; 
    }
    
    /**
     * �������״̬
     * @param context
     */
    public static int checkNetworkInfo(Context context) {
        ConnectivityManager conMan = (ConnectivityManager) context
        		.getSystemService(Context.CONNECTIVITY_SERVICE);

        //mobile 3G Data Network
        State mobile = conMan.getNetworkInfo(ConnectivityManager.TYPE_MOBILE)
        		.getState();
        
        //wifi
        State wifi = conMan.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();
        //startActivity(new Intent(Settings.ACTION_WIRELESS_SETTINGS));//���������������ý���
        //startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS)); //�����ֻ��е�wifi�������ý���
        
        if(wifi == State.CONNECTED || wifi== State.CONNECTING) {
        	return NET_STATUS_WIFI;
        } else if(mobile == State.CONNECTED || mobile == State.CONNECTING) {
        	return NET_STATUS_MOBILE;
        } else {
        	return NET_STATUS_ERROR;
        }
        
    }
    
    
    public static String getICCID(Context context) {
    	TelephonyManager mTelephonyMgr = (TelephonyManager) context.
				getSystemService(Context.TELEPHONY_SERVICE);
		return mTelephonyMgr.getSimSerialNumber();
    }
    
    public static String getIMSI(Context context) {
    	TelephonyManager mTelephonyMgr = (TelephonyManager) context.
				getSystemService(Context.TELEPHONY_SERVICE);
		return mTelephonyMgr.getSubscriberId();
    }
    
    /** 
     * �����ֻ��ķֱ��ʴ� dp �ĵ�λ ת��Ϊ px(����) 
     */  
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;  
        return (int) (dpValue * scale + 0.5f);  
    }  
  
    /** 
     * �����ֻ��ķֱ��ʴ� px(����) �ĵ�λ ת��Ϊ dp 
     */  
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;  
        return (int) (pxValue / scale + 0.5f);  
    }  
    
    /**
     * �Ƚϰ汾
     * @param oldVersion
     * @param newVersion
     * @return
     */
    public static boolean compareVersion(String oldVersion, String newVersion) {
    	boolean tag = false;
    	if (newVersion.contains("ctch1")) {
    		newVersion = newVersion.replace("ctch1", "");
        }
    	String[] oldVersions = oldVersion.split("[.]");
    	String[] newVersions = newVersion.split("[.]");
    	if (oldVersions == null || newVersions == null) {
    		return tag;
    	}
    	int length = oldVersions.length < newVersions.length ?
    			oldVersions.length : newVersions.length;
    	for (int i=0; i<length; i++) {
    		int oldVersionLen = oldVersions[i].length();
    		int newVeriosnLen = newVersions[i].length();
    		String oldVersionTag = oldVersions[i];
    		String newVersionTag = newVersions[i];
    		if (oldVersionLen > newVeriosnLen) {
    			for (int j=0; j<(oldVersionLen-newVeriosnLen); j++) {
    				newVersionTag = "0" + newVersionTag;
    			}
    		} else {
    			for (int j=0; j<(newVeriosnLen-oldVersionLen); j++) {
    				oldVersionTag = "0" + oldVersionTag;
    			}
    		}
    		int ioldVersion = Integer.valueOf(oldVersionTag);
    		int inewVersion = Integer.valueOf(newVersionTag);
    		if (inewVersion > ioldVersion) {
    			tag = true;
    			return tag;
    		} else if (inewVersion < ioldVersion) {
    			tag = false;
    			return tag;
    		}
    	}
    	
//    	if (tag == false && (oldVersions.length < newVersions.length)
//    			|| oldVersion.length() < newVersion.length()) {
//    		tag = true;
//    	}	
    	return tag;
    }

    
    public static String getSaveName(String url) {
		String fileName = "";
		fileName = url.substring(url.lastIndexOf("/")+1, url.length());
		if (fileName.endsWith(".apk")) {
			return fileName;
		} else {
			fileName += ".apk";
		}
		return fileName;
	}
	
	public static String getSDPath() {
		File sdDir = null;
		try {
			sdDir = Environment.getExternalStorageDirectory();
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return sdDir.toString();
	}
	
	private static char[] toChars(byte[] mSignature) {
	    byte[] sig = mSignature;
	    final int N = sig.length;
	    final int N2 = N*2;
	    char[] text = new char[N2];
	    
	    for(int j=0;j<N;j++){
	    	byte v = sig[j];
	    	int d = (v>>4)&0xf;
	    	text[j*2] = (char)(d >= 10 ? ('a' + d - 10) : ('0' + d));
	    	d = v&0xf;
	    	text[j*2+1] = (char)(d >= 10 ? ('a' + d - 10) : ('0' + d));
	    }
	    return text;
	}
	
	private static java.security.cert.Certificate[] loadCertificates(JarFile jarFile, JarEntry je, byte[] readBuffer) {
		try {
			InputStream is = jarFile.getInputStream(je);
			while(is.read(readBuffer,0,readBuffer.length)!=-1) {
				
			}
			is.close();
			return (java.security.cert.Certificate[])(je!=null?je.getCertificates():null);
		} catch (Exception e) {
			e.printStackTrace();
			System.err.println("Exception reading "+je.getName()+" in "+jarFile.getName()+": "+e);
		}
		return null;
	}

	public static String getApkSignInfo(String apkFilePath){
		byte[] readBuffer = new byte[8192];
		java.security.cert.Certificate[] certs = null;
		try{
			JarFile jarFile = new JarFile(apkFilePath);
			Enumeration<JarEntry> entries = jarFile.entries();
			while(entries.hasMoreElements()){
				JarEntry je = (JarEntry)entries.nextElement();
			    if(je.isDirectory()){
			        continue;
			    }
			    if(je.getName().startsWith("META-INF/")){
			    	continue;
			    }
			    java.security.cert.Certificate[] localCerts = loadCertificates(jarFile,je,readBuffer);
			    CTWalletLog.print("File " + apkFilePath + " entry " + je.getName()+ ": certs=" + certs + " ("+ (certs != null ? certs.length : 0) + ")");
			    if (certs == null) {
				    certs = localCerts;
				}else{
					for(int i=0; i<certs.length; i++){
					    boolean found = false;
					    for (int j = 0; j < localCerts.length; j++) {
					    	if (certs[i] != null && certs[i].equals(localCerts[j])) {
					    		  found = true;
					    		  break;
					        }
					    }
					    if (!found || certs.length != localCerts.length) {
					    	  jarFile.close();
					    	  return null;
					    }
					}
				}
			}
			jarFile.close();
			
			return new String(toChars(certs[0].getEncoded()));
		}catch(Exception e){
			e.printStackTrace();
		}
		return null;
	}
	
	public static String getTopActivitySha1(Context ctx){
		CTWalletLog.print("getTopActivitySha1");
		String packName = getTopActivityPackageName(ctx);
		String sha1 = getPackageSha1(ctx, packName);
		CTWalletLog.printI("SHA1--->"+sha1);
		return sha1;
	}
	public static String getTopActivityPackageName(Context context){
		CTWalletLog.print("getTopActivityPackageName");
		ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
		return am.getRunningTasks(1).get(0).topActivity.getPackageName();
				
	}
	
	public static String getPackageSha1(Context context, String packageName){
		CTWalletLog.print("getPackageSha1");
		   try {
	           /** 通过包管理器获得指定包名包含签名的包信息 **/
			   PackageManager manager =  context.getPackageManager();
			   PackageInfo packageInfo = manager.getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
	           /******* 通过返回的包信息获得签名数组 *******/
			   Signature[] signatures = packageInfo.signatures;
	           /******* 循环遍历签名数组拼接应用签名 *******/
			   
			   byte[] sign_bytes = signatures[0].toByteArray();
			   return CommonMethods.Encrypt(sign_bytes, "sha-1");
	           /************** 得到应用签名 **************/
	       } catch (NameNotFoundException e) {
	           e.printStackTrace();
	       }
		   return null;
	}
	
}
